<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/16
 * 描述:
 */

namespace app\result;

use app\model\Cart;
use app\model\goods\Goods;
use app\model\goods\GoodsSpecPrice;
use app\model\user\UserAddress;

class CartResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Cart();
    }

    public function list($user_id, $args = []): array
    {
        $where = [];
        $where['a.user_id'] = $user_id;
        $data = $this->model->alias('a')
            ->join('goods b', 'a.goods_id=b.goods_id', 'left')
            ->join('goods_spec_price c', 'a.spec_id=c.spec_id', 'left')
            ->field('a.id,a.goods_id,a.spec_id,a.goods_num,b.is_sku,b.goods_name,b.goods_image,c.spec_name,b.del_time,b.goods_id as source_goods_id,b.is_on_sale,c.spec_id as spec_source_id')
            ->field('b.goods_price,c.price')
            ->where($where)
            ->group('a.id')
            ->order('a.id desc')
            ->select();
        if ($data) {
            foreach ($data as &$v) {
                $v['goods_price'] = $v['spec_id'] > 0 ? $v['price'] : $v['goods_price'];
                $v['total_price'] = $v['goods_num'] * $v['goods_price'];
                if (empty($v['source_goods_id']) || !empty($v['del_time']) || $v['is_on_sale'] == 0) {
                    $v['goods_name'] = '商品已下架，请购买其它商品！！！';
                    $v['goods_image'] = request()->domain() . '/static/image/xiajia.png';
                    $v['goods_price'] = '0.00';
                    $v['spec_name'] = '';
                }
                if ($v['is_sku'] && empty($v['spec_source_id'])) {
                    $v['goods_image'] = request()->domain() . '/static/image/maiwan.png';
                    $v['goods_price'] = '0.00';
                    $v['spec_name'] = '次规格已售罄，请选择其它规格！！';
                }
                $v['spec_name'] = $v['spec_name'] ?? '';
            }
            unset($v);
        }
        return self::success_return('success', [
            'list' => $data
        ]);
    }

    public static function current_cart_num($user_id)
    {
        $num = (new Cart())->data_sum(['user_id' => $user_id], 'goods_num');
        return max($num, 0);
    }

    public function action($user_id, $args = [])
    {
        $goods_id = $args['item_id'] ?? "";
        $spec_id = intval($args['spec_id'] ?? "0");
        $goods_num = intval($args['goods_num'] ?? "1");
        if (empty($goods_id)) {
            return self::error_return('请选择要添加的商品');
        }
        if ($goods_num <= 0) {
            return self::error_return('商品数量应大于0');
        }
        $goods = (new Goods())->data_get(['goods_id' => $goods_id, 'is_on_sale' => 1], 'goods_id,goods_name');
        if (!$goods) {
            return self::error_return('商品已售罄');
        }
        if ($spec_id) {
            $spec_price = (new GoodsSpecPrice())->data_get(['spec_id' => $spec_id, 'goods_id' => $goods_id]);
            if (!$spec_price) {
                return self::error_return('商品规格已售罄');
            }
        }
        $baseData = [
            'user_id' => $user_id,
            'goods_id' => $goods_id,
            'spec_id' => $spec_id,
            'goods_num' => $goods_num,
        ];
        $has = $this->model->data_get(['user_id' => $user_id, 'goods_id' => $goods_id, 'spec_id' => $spec_id]);
        if ($has) {
            (new Cart())->data_update(['id' => $has['id']], ['goods_num' => $goods_num]);
        } else {
            (new Cart())->data_add($baseData);
        }

        return self::success_return('保存成功', [
            'cart_total_num' => self::current_cart_num($user_id)
        ]);
    }

    public function delete($user_id, $args = [])
    {
        $ids = $args['ids'];
        if (empty($ids)) {
            return self::error_return('请选择要移除的商品');
        }
        $where = [['user_id', '=', $user_id]];
        if (is_array($ids)) {
            $where[] = ['id', 'in', $ids];
        } else {
            $where[] = ['id', '=', $ids];
        }
        $this->model->data_del($where);
        return self::success_return('删除成功');
    }

    //预结算
    public function checkout($user_id, $args = [])
    {
        $order_type = $args['order_type'] ?? 'buyNow';
        $address_id = $args['address_id'] ?? "";
        $getGoodsList = $this->get_goods_list($user_id, $args, $order_type == 'buyNow' ? 'buyNow' : 'cart');
        if ($getGoodsList['code'] !== 0) {
            return $getGoodsList;
        }
        $data = $getGoodsList['data'];
        if (empty($data)) {
            return self::error_return('请选择要购买的商品');
        }
        $order_total_price = 0;
        $actual_pay_price = 0;//应付款
        $order_total_num = 0;
        foreach ($data as $v) {
            $order_total_price = bcadd($order_total_price, $v['total_price'], 2);
            $order_total_num = bcadd($order_total_num, $v['total_num']);
            $actual_pay_price = bcadd($actual_pay_price, $v['total_price'], 2);
        }
        $needAddress = true;
        //1=常规商品，2=虚拟商品
        if ($data[0]['goods_type'] == 2) {
            $needAddress = false;
        }
        if ($needAddress) {
            $whereAddress = [['user_id', '=', $user_id]];
            if ($address_id) {
                $whereAddress[] = ['address_id', '=', $address_id];
            }
            $address = (new UserAddress())->data_get($whereAddress, '*', 'is_default desc');
        }

        $coupon_list = (new CouponResult())->order_coupon($user_id, $order_total_price);
        return self::success_return('success', [
            'goods_list' => $data,
            'need_address' => $needAddress,
            'address' => $address ?? null,
            "shipping_fee" => "0.00",
            "coupon_list" => $coupon_list,
            "order_total_num" => $order_total_num,
            "order_total_price" => $order_total_price,
            "actual_pay_price" => $actual_pay_price,
            "order_pay_price" => $actual_pay_price,
        ]);

    }

    public function get_goods_list($user_id, $args, $type = 'buyNow'): array
    {
        if ($type !== 'buyNow') {
            $cart_ids = $args['cart_ids'] ?? "";
            $cart_ids = array_filter(explode(',', $cart_ids));
            if (empty($cart_ids)) {
                return self::error_return('请选择要购买的商品');
            }
            $where = [['a.user_id', '=', $user_id]];
            $where[] = ['a.id', 'in', $cart_ids];
            $data = $this->model->alias('a')
                ->join('goods b', 'a.goods_id=b.goods_id', 'left')
                ->join('goods_spec_price c', 'a.spec_id=c.spec_id', 'left')
                ->field('a.id,a.goods_id,a.spec_id,a.goods_num,b.goods_name,b.store_count,b.goods_image,c.spec_name')
                ->field('b.goods_price,c.spec_id,c.price,c.spec_name,c.store_count as spec_store_count,b.del_time,b.goods_id as source_goods_id,b.is_on_sale,b.goods_type')
                ->where($where)
                ->group('a.id')
                ->select();
            if (!$data) {
                return self::error_return('商品已售罄');
            }
            $data = $data->toArray();
            $goods_types = array_unique(array_column($data, 'goods_type'));
            if (count($goods_types) > 1) {
                return self::error_return('虚拟商品和实物商品不能同时购买！！！');
            }
            //$goodsType = $goods_types[0] == 1 ? 1 : 2;//1=常规商品，2=虚拟商品
            foreach ($data as &$v) {
                $v['goods_price'] = $v['spec_id'] > 0 ? $v['price'] : $v['goods_price'];
                $v['store_count'] = $v['spec_id'] > 0 ? $v['spec_store_count'] : $v['store_count'];
                $v['total_price'] = $v['goods_num'] * $v['goods_price'];
                $v['total_num'] = $v['goods_num'];
                if (empty($v['source_goods_id']) || !empty($v['del_time']) || $v['is_on_sale'] == 0) {
                    return self::error_return('存在已下架商品，请重新选择！！！');
                }
            }
            unset($v);
            return self::success_return('success', $data);
        } else {
            $goods_num = $args['goods_num'] ?? "";
            $goods_id = $args['item_id'] ?? "";
            $spec_id = $args['spec_id'] ?? "";
            if (empty($goods_id)) {
                return self::error_return('请选择要购买的商品');
            }
            if (empty($goods_num)) {
                return self::error_return('请填写购买数量');
            }
            $goods = (new Goods())->data_get(['goods_id' => $goods_id, 'is_on_sale' => 1], 'goods_id,goods_name,goods_image,goods_price,store_count,goods_type');
            if (!$goods) {
                return self::error_return('商品已售罄');
            }
            $goods = $goods->toArray();
            if (!empty($spec_id)) {
                $spec_price = (new GoodsSpecPrice())->data_get(['spec_id' => $spec_id, 'goods_id' => $goods_id]);
                if (!$spec_price) {
                    return self::error_return('商品规格已售罄');
                } elseif ($spec_price['store_count'] < $goods_num) {
                    return self::error_return('商品规格库存不足');
                }
                $goods['goods_price'] = $spec_price['price'];
                $goods['store_count'] = $spec_price['store_count'];
                $goods['spec_id'] = $spec_price['spec_id'];
                $goods['spec_name'] = $spec_price['spec_name'];
                $goods['total_num'] = $goods_num;
                $goods['total_price'] = $goods_num * $spec_price['price'];
            } else {
                $goods['total_num'] = $goods_num;
                $goods['total_price'] = $goods_num * $goods['goods_price'];
                $goods['spec_name'] = '';
                $goods['spec_id'] = 0;
            }
            return self::success_return('success', [$goods]);
        }
    }


}
